package background;

import database.DataBaseConnection;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

public class DailyJob implements Runnable {

    @Override
    public void run() {
        Connection connection = DataBaseConnection.getConnection();
        if (connection != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH-mm-ss");
            String end = this.getEndTime();
            String filepath = String.format("%s_%s.csv", end, simpleDateFormat.format(new Date()));
            String sql = "SELECT * INTO OUTFILE '" + filepath + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED "
                    + "BY '\"' LINES TERMINATED BY '\n' FROM encryption where execute_time < '" + end + "'";
            try {
                Statement statement = connection.createStatement();
                statement.executeQuery(sql);
                System.out.println(simpleDateFormat.format(new Date()));
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DataBaseConnection.closeConnection(connection);
            }
        }
    }

    private String getEndTime() {
        Properties properties = new Properties();
        InputStreamReader inputStreamReader = null;
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("backgroundJob.properties");
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            properties.load(inputStreamReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String span = properties.getProperty("span");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, Integer.parseInt(span) * (-1));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return simpleDateFormat.format(calendar.getTime());
    }
}
